﻿using System;
using System.Linq;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.SharePoint.Deployment;
using System.IO;
using CodeCounsel.SharePoint.DevTools.Commands;
using Microsoft.VisualStudio.SharePoint.Packages;

namespace CodeCounsel.SharePoint.DevTools.DeploymentSteps
{
    [Export(typeof(IDeploymentStep))]
    [DeploymentStep(DeploymentStepIds.InstallFeatures)]
    public class InstallFeatures
        : IDeploymentStep
    {
        public void Initialize(IDeploymentStepInfo stepInfo)
        {
            stepInfo.Name = "Install Features";
            stepInfo.StatusBarMessage = "Installing Features...";
            stepInfo.Description = "Installs the SharePoint Features that are packaged in the project.";
        }

        public bool CanExecute(IDeploymentContext context)
        {
            bool canExecute = context.Project.IsSandboxedSolution == false;
            if (canExecute == false)
            {
                context.Logger.WriteLine("Skipping step because the project is configured to deploy into the solution sandbox.", LogCategory.Status);
            }
            return canExecute;
        }

        public void Execute(IDeploymentContext context)
        {
            foreach (ISharePointProjectFeature feature in context.Project.Package.Features)
            {
                string relativePath = Path.Combine(ProjectUtilities.UnTokenize(feature, feature.Model.DeploymentPath), "Feature.xml");
                context.Project.SharePointConnection.ExecuteCommand<string>(CommandIDs.InstallFeature, relativePath);
            }
        }
    }
}